package web;

import com.alibaba.fastjson2.JSONObject;
import dao.impl.StudentDaoImpl;
import domain.Student;
import service.IStudentService;
import service.impl.IStudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 于金鹏
 * @Date 2024/12/12 16:44
 * @Package yujinpeng
 */
@WebServlet("/getStudent")
public class StudentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, IOException {
        // 一、获取请求信息
        // 解决乱码问题
        req.setCharacterEncoding("utf-8");
        // 解析请求体中的参数
        // 1. 获取输入流
        BufferedReader reader = req.getReader();
        // 2. 获取请求的完整信息
        StringBuilder requestBodyJsonStr = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            requestBodyJsonStr.append(line);
        }
        // 3, 将字符串信息解析承json对象
        Student student = JSONObject.parseObject(requestBodyJsonStr.toString(), Student.class);
        if (student == null) {
            student = new Student();
        }
        // 二、进行业务逻辑处理，组装返回数据
        try {
            IStudentService studentService = new IStudentServiceImpl(new StudentDaoImpl());
            List<Student> list = studentService.getStudents(student);
            // 三、进行数据响应
            resp.setContentType("application/json;charset=utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().write(JSONObject.toJSONString(list));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
